/**
 * SmsService.java 
 * Copyright © 2014-2016, 杭州泊享网络科技有限公司
 * 
 * @author Liu Tao
 * @create 2015年5月30日
 */
package com.pshare.msg.sms.service;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.pshare.constant.SeaxConstants;
import com.pshare.framework.annotation.CachePutx;
import com.pshare.framework.annotation.Cacheablex;
import com.pshare.framework.validator.TelephoneValidator;
import com.pshare.msg.sms.service.impl.LdSmsTask;

/**
 * 短信接口
 */
@Service
public class SmsService {

	private static final Logger logger = Logger.getLogger(SmsService.class);
	
	protected static ExecutorService exec = Executors.newCachedThreadPool();
	
//	public abstract void sendMsg(String cellphone, String message);
	
	public void send(String cellphone, String message) {
		if (!TelephoneValidator.isCellphone(cellphone)) {
			logger.warn("cellphone is invalid: " + cellphone);
			return;
		}
		
		// 防止骚扰
		if (!allowSend(cellphone)) {
			logger.warn("not allowed send sms to cellphone " + cellphone + " in 10 minutes");
			return;
		}
		
		exec.submit(new LdSmsTask(cellphone, message));
	}
	

	
	/**
	 * 记录10分钟内发送次数（非精确）
	 * @param cellphone
	 * @param sendTimes
	 * @return Integer
	 */
	@CachePutx(value = "smslock#" + SeaxConstants.EXPIRE_TIME_SMS, key = "#cellphone")
	public Integer recordTimes(String cellphone, Integer sendTimes) {
		if (sendTimes == null) {
			sendTimes = 1;
		} else {
			sendTimes++;
		}

		return sendTimes;
	}
	
	/**
	 * 读取规定时间内发送次数（非精确）
	 * @param cellphone
	 * @return Integer
	 */
	@Cacheablex(value = "smslock#" + SeaxConstants.EXPIRE_TIME_SMS, key = "#cellphone")
	public Integer getSendTimes(String cellphone) {
		logger.info("get locked account for " + cellphone);
		return null;
	}
	
	/**
	 * 判断手机号是否允许发送，如果在10分钟内发送了超过10次，则不允许发送
	 * @param cellphone
	 * @return boolean
	 */
	protected boolean allowSend(String cellphone) {
		Integer sendTimes = getSendTimes(cellphone);
		if (sendTimes == null) {
			sendTimes = 0;
		}
		if (sendTimes < 10) {
			// 继续加1
			recordTimes(cellphone, sendTimes + 1);
			return true;
		}
		return false;
	}
	
	
}
